package video.dali.controller;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import video.dali.common.PageResult;
import video.dali.common.Result;
import video.dali.common.dto.CategoryPageDto;
import video.dali.common.dto.UserVideo;
import video.dali.common.dto.VideoDto;
import video.dali.common.dto.VideosCategoryPageDto;
import video.dali.common.entity.Video;
import video.dali.common.vo.VideoVo;
import video.dali.service.CategoryService;
import video.dali.service.VideoService;


import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping("/video")
@Slf4j
public class VideoController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 上传文件
     * @param id
     * @param files
     * @return
     * @throws IOException
     */
    @PostMapping("/upload/{id}/{categoryId}")
    public Result upload(@PathVariable("id") Integer id,
                         @PathVariable("categoryId") int categoryId,
                         @RequestBody List<MultipartFile> files) throws IOException {
        for (MultipartFile file : files) {
            log.info("上传文件:{}",file.getOriginalFilename());
        }
        VideoDto videoDto = new VideoDto();
        videoDto.setCategoryId(categoryId);
        videoDto.setUserId(id);
        videoDto.setFiles(files);
        videoService.upload(videoDto);
        return Result.success();
    }


    /**
     * 删除视频
     * @param userVideo
     * @return
     */
    @DeleteMapping("/delete")
    public Result deleteUSerVideo(@RequestBody UserVideo userVideo) throws IOException {
        log.info("删除用户视频,id:{},userId:{}",userVideo.getId(),userVideo.getUserId());
        videoService.deleteUserVideo(userVideo);
        return Result.success();
    }


    /**
     * 根据userId查询视频
     * @param
     * @return
     */
    @GetMapping("/list")
    public Result<List<Video>> listByUserId(){
        log.info("根据userId查询视频");
        List<Video> videoList = videoService.listByUserId();
        return Result.success(videoList);
    }


    /**
     * 查询所有视频分类
     * @return
     */
    @GetMapping("/page/category")
    public Result<PageResult> listAllCategoryPage(CategoryPageDto categoryPageDto){
        log.info("查询所有视频分类，page:{},pageSize:{},name:{}",categoryPageDto.getPage(),categoryPageDto.getPageSize(),categoryPageDto.getName());
        return Result.success(categoryService.listAllCategoryPage(categoryPageDto));
    }


    /**
     * 根据id查询视频url
     * @param id
     * @return
     */
    @GetMapping("/getVideoUrl")
    public Result<VideoVo> getById(@RequestParam("videoId") Integer id){
        log.info("根据id查询视频,id:{}",id);
        VideoVo videoVo = videoService.getById(id);
        String address = videoVo.getAddress();
        String videoUrl = "http://localhost:8081/"+address;
        videoVo.setAddress(videoUrl);
        log.info("视频url = {}", videoVo.getAddress());
        return Result.success(videoVo);
    }


    /**
     * 根据分类id查询视频
     * @param videosCategoryPageDto
     * @return
     */
    @GetMapping("/category")
    public Result<PageResult> getVideosByCategoryId(VideosCategoryPageDto videosCategoryPageDto){
        log.info("根据分类id查询视频");
        PageResult pageResult =  videoService.getVideosByCategoryId(videosCategoryPageDto);
        return Result.success(pageResult);
    }



    private static final String VIDEO_FILES_DIR = "C:\\Users\\young\\Desktop\\repos\\dali\\src\\main\\resources\\static\\videos\\dager\\";

    @GetMapping("/getVideo")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("videoId") Integer id) throws IOException {
        log.info("获取视频");
        VideoVo videoVo = videoService.getById(id);
        String filename = videoVo.getName()+".mp4";
        File file = new File(VIDEO_FILES_DIR + filename);
        InputStream inputStream = Files.newInputStream(file.toPath());
        ResponseEntity<InputStreamResource> body = ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                .contentType(MediaType.parseMediaType("video/mp4"))
                .contentLength(file.length())
                .body(new InputStreamResource(inputStream));
        return body;
    }
//    public ResponseEntity<InputStreamResource> downloadVideo(@RequestParam("videoId") Integer id) {
//        log.info("获取视频");
//        VideoVo videoVo = videoService.getById(id);
//        String filename = videoVo.getName()+".mp4";
//        File videoFile = new File(VIDEO_FILES_DIR + filename);
//        log.info("视频文件路径 = "+VIDEO_FILES_DIR + filename);
//        if (!videoFile.exists() || !videoFile.isFile()) {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
//        }
//
//        try (InputStream inputStream = Files.newInputStream(videoFile.toPath())) {
//            HttpHeaders headers = new HttpHeaders();
//            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + videoFile.getName() + "\"");
//            headers.add(HttpHeaders.CONTENT_TYPE, "video/mp4"); // 或者根据文件类型设置正确的MIME类型
//            headers.setContentLength(videoFile.length());
//            log.info("响应头 = {}", headers);
//            InputStreamResource resource = new InputStreamResource(inputStream);
//            ResponseEntity<InputStreamResource> body = ResponseEntity.ok()
//                    .headers(headers)
//                    .body(resource);
//            log.info("构造完成");
//            return body;
//        } catch (IOException e) {
//            // 记录错误日志
//            e.printStackTrace();
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
//        }
//    }



//    // 假设视频文件存储在类路径下的/videos/目录中
//    private static final String VIDEO_DIR = "/videos/";
//
//    // 使用@GetMapping来映射视频文件的URL
//    @GetMapping("/videos/{filename:.+}")
//    public ResponseEntity<byte[]> getVideo(@PathVariable String filename) {
//        try {
//            // 加载视频文件资源
//            Resource resource = new ClassPathResource(VIDEO_DIR + filename);
//            Path path = Paths.get(resource.getURI());
//
//            // 读取文件内容到字节数组
//            byte[] videoBytes = Files.readAllBytes(path);
//
//            // 设置HTTP响应头
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.parseMediaType("video/mp4")); // 根据你的视频文件格式设置正确的MIME类型
//            headers.setContentLength(videoBytes.length);
//
//            // 返回视频文件内容作为响应体
//            return new ResponseEntity<>(videoBytes, headers, HttpStatus.OK);
//
//        } catch (IOException e) {
//            // 处理文件读取错误
//            e.printStackTrace();
//            return new ResponseEntity<>(HttpStatus.NOT_FOUND); // 返回404状态码表示文件未找到
//        }
//    }


}
